{% extends 'layout/manage.html' %}
{% load static %}
{% block css %}
    <link rel="stylesheet" href="{% static 'plugins/editor-md/css/editormd.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-datepicker/css/bootstrap-datepicker.min.css' %}">
    <link rel="stylesheet" href="{% static 'plugins/bootstrap-select/css/bootstrap-select.min.css' %}">
    <style>

        .comment-area .item {
            margin-top: 20px;
        }

        .comment-area .left-avatar {
            float: left;
            margin-right: 10px;
            display: inline-block;
            width: 30px;
            height: 30px;
            background-color: #304659;
            color: white;
            text-align: center;
            line-height: 30px;
            border-radius: 50%;
        }

        .comment-area .right-info {
            padding-left: 35px;
        }

        .comment-area .right-info .desc .msg {
            display: inline-block;
            padding-right: 20px;
            color: #8c8c8c;
        }

        .comment-area .child {
            padding-left: 55px;
        }

        .comment-area .error-msg {
            color: red;
        }

        .comment-area .reply-user {
            display: inline-block;
            background-color: #ddd;
            color: black;
            padding: 6px 8px;
            margin-left: 20px;
            border-radius: 8px;
            cursor: pointer;
        }

        .editormd-fullscreen {
            z-index: 1001;
        }
    </style>
{% endblock %}
{% block content %}
    <div class="container-fluid clearfix" style="margin-top: 60px">
        <div class="col-sm-6">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="fa fa-search" aria-hidden="true"></i> 详情
                </div>
                <div class="panel-body">
                    <form id="addForm" class="form-horizontal">
                        {% csrf_token %}
                        <div class="form-group">
                            <label for="{{ form.issues_type.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.issues_type.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.issues_type }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.subject.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.subject.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.subject }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.milestone.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.milestone.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div>
                                        {{ form.milestone }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>
                        <div class="form-group">
                            <label for="{{ form.desc.id_for_label }}"
                                   class="col-md-2 control-label">{{ form.desc.label }}</label>
                            <div class="col-md-10">
                                <div>
                                    <div id="editor">
                                        {{ form.desc }}
                                    </div>

                                    <div class="error-msg"></div>
                                </div>
                                <div class="error-msg"></div>
                            </div>
                        </div>

                        <div class="form-group clearfix">

                            <div class="col-md-6 pd-0">
                                <label for="{{ form.status.id_for_label }}"
                                       class="col-md-4 control-label">{{ form.status.label }}</label>
                                <div class="col-md-8 clearfix">
                                    <div>
                                        {{ form.status }}
                                    </div>
                                    <div class="error-msg"></div>

                                </div>
                            </div>
                            <div class="col-md-6 pd-0">
                                <label for=" {{ form.priority.id_for_label }}"
                                       class="col-md-4 control-label">{{ form.priority.label }}</label>
                                <div class="col-md-8">
                                    <div>
                                        {{ form.priority }}
                                    </div>
                                    <div class="error-msg"></div>

                                </div>
                            </div>
                        </div>

                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">指派给</label>
                                <div class="col-md-8">
                                    {{ form.assign }}
                                    <div class="error-msg"></div>
                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">关注者</label>
                                <div class="col-md-8">

                                    {{ form.attention }}

                                    <div class="error-msg"></div>
                                </div>
                            </div>
                        </div>

                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">开始时间</label>
                                <div class="col-md-8">

                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon2">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.start_date }}
                                    </div>
                                    <span class="error-msg"></span>

                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">截止时间</label>
                                <div class="col-md-8">

                                    <div class="input-group">
                                        <span class="input-group-addon" id="sizing-addon2">
                                            <i class="fa fa-calendar" aria-hidden="true"></i>
                                        </span>
                                        {{ form.end_date }}
                                    </div>
                                    <span class="error-msg"></span>
                                </div>
                            </div>
                        </div>
                        <div class="form-group clearfix">
                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label">模式</label>
                                <div class="col-md-8">
                                    <div>
                                        {{ form.mode }}
                                    </div>
                                    <div class="error-msg"></div>
                                </div>
                            </div>

                            <div class="col-md-6 pd-0">
                                <label for="inputPassword3" class="col-md-4 control-label"> 父问题</label>
                                <div class="col-md-8">

                                    {{ form.parent }}

                                    <div class="error-msg"></div>
                                </div>
                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>
        <div class="col-sm-6">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <i class="fa fa-search" aria-hidden="true"></i> 操作记录&回复
                </div>
                <div class="panel-body comment-area">

                    <div class="comment-list">


                    </div>

                    <hr/>
                    <div class="comment-text" id="commentText">

                        <div class="form-group">
                            <textarea id="content" rows="6" class="form-control"
                                      placeholder="请输入要回复的内容"></textarea>
                            <span class="error-msg"></span>
                        </div>

                        <input class="btn btn-primary" type="button" id="btnSubmit" value="提 交">
                        <div class="reply-user hide" id="replyUser">
                            回复 <span></span>
                            <i class="fa fa-times-circle" aria-hidden="true" style="color: #9d9d9d;"></i>
                        </div>
                    </div>


                </div>
            </div>
        </div>
    </div>
    <div class="hide" id="recordTemplate">
        <div class="item clearfix">
            <div class="left-avatar"></div>
            <div class="right-info">
                <pre></pre>
                <div class="desc">
                    <div class="msg">
                        <i class="fa fa-bullhorn" aria-hidden="true"></i>
                        <span class="type"></span>
                    </div>
                    <div class="msg">
                        <i class="fa fa-user-o" aria-hidden="true"></i>
                        <span class="user"></span>
                    </div>
                    <div class="msg">
                        <i class="fa fa-clock-o" aria-hidden="true"></i>
                        <span class="date"></span>
                    </div>

                    <a href="#commentText" class="reply">
                        <i class="fa fa-commenting-o" aria-hidden="true"></i> 回复
                    </a>

                </div>
            </div>
            <div class="child">

            </div>
        </div>
    </div>
{% endblock %}
{% block js %}
    <script src="{% static 'plugins/editor-md/editormd.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-datepicker/js/bootstrap-datepicker.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-select/js/bootstrap-select.min.js' %}"></script>
    <script src="{% static 'plugins/bootstrap-select/js/i18n/defaults-zh_CN.min.js' %}"></script>
    <script>
        var initReplyURL = "{% url 'issues_reply' project_id=request.tracer.project.id issues_id=issues_object.id %}";
        var IssuesChangeURL = "{% url 'issues_change' project_id=request.tracer.project.id issues_id=issues_object.id %}";
        var WIKI_UPLOAD_URL = "{% url 'wiki_uploads' project_id=request.tracer.project.id wiki_id=0 %}";
        $(function () {
            //初始化
            initReply();
            //
            initDatePicker();
            // 初始化markdown编辑器
            initEditorMd();
            // 绑定回复按钮的点击事件
            bindClickReply();
            // 绑定取消回复按钮的点击事件
            bindCancelClickReply();
            // 绑定提交回复按钮的点击事件
            bindSubmitReply();
            // 绑定onchange事件
            bindOnChange();
        })

        /* 添加对话框：初始化时间选择 */
        function initDatePicker() {

            $('#id_start_date,#id_end_date').datepicker({
                format: 'yyyy-mm-dd',
                startDate: '0',
                language: "zh-CN",
                autoclose: true
            });
        }

        /* 初始化markdown编辑器（textare转换为编辑器） */
        function initEditorMd() {
            EDITOR = editormd('editor', {
                placeholder: "请输入内容",
                height: 300,
                path: "{% static 'plugins/editor-md/lib/' %}",
                imageUpload: true,
                imageFormats: ["jpg", 'jpeg', 'png', 'gif'],
                imageUploadURL: WIKI_UPLOAD_URL,
                toolbarAutoFixed: false,
                toolbarIcons: function () {
                    return ["bold", "hr", "del", "italic", "quote", "|", "image", "preview", "watch", "fullscreen", "||", "save"]
                },
                toolbarCustomIcons: {
                    save: "<input type='button' value='保 存' class='btn btn-success btn-sm' onclick='saveDesc();' />"
                },
                onload: function () {
                    this.previewing();
                }
            })
        }

        // 创建回复节点
        function createRecordNode(nodeDict) {
            //复制回复模板
            var $item = $("#recordTemplate").find(".item").clone();
            $item.find(".left-avatar").html(nodeDict.creator[0].toUpperCase());
            $item.find('pre').html(nodeDict.content);
            $item.find('.type').html(nodeDict.reply_type_text);
            $item.find('.user').html(nodeDict.creator);
            $item.find('.date').html(nodeDict.datetime);
            $item.attr({id: nodeDict.id, username: nodeDict.creator});

            if (nodeDict.parent_id) {
                // 如果又父级 则挂在谁下
                $('#' + nodeDict.parent_id).children('.child').append($item);
            } else {
                // 挂在根下
                $(".comment-list").append($item);
            }
        }

        // 初始化回复
        function initReply() {
            $.ajax({
                url: initReplyURL,
                type: "GET",
                date: "",
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        //成功获取到回复数据
                        if (res.data.length) {
                            $.each(res.data, function (index, value) {
                                createRecordNode(value);
                            });
                        } else {
                            //没有任何数据
                            $(".comment-list").append("<b id='nothing'>没有任何回复.</b>");
                        }

                    } else {
                        //回复数据获取失败
                        $(".comment-list").append("<b>数据拉取失败.</b>");
                    }

                }
            })
        }

        /* 绑定点击回复按钮的点击事件 */
        function bindClickReply() {
            $(".comment-list").on('click', '.reply', function () {
                // 找到按钮的父级，并获取属性值
                var $reply_btn = $(this).parent().parent().parent();
                var id = $reply_btn.attr('id');
                var username = $reply_btn.attr('username');
                // 移除 隐藏 、设置 parent-id属性、添加子元素 span
                $('#replyUser').removeClass('hide').attr('parent-id', id).children('span').text(username);
            })
        }

        /* 绑定取消回复按钮的点击事件 */
        function bindCancelClickReply() {
            $('#replyUser').click(function () {
                $(this).addClass('hide').removeAttr('parent-id').children('span').text("");
            })
        }

        /* 点击提交评论按钮 */
        function bindSubmitReply() {
            $("#btnSubmit").click(function () {
                $("#commentText .error-msg").text("");
                $.ajax({
                    url: initReplyURL,
                    type: "POST",
                    data: {content: $('#content').val(), reply: $("#replyUser").attr('parent-id')},
                    dataType: "JSON",
                    success: function (res) {
                        if (res.status) {
                            //
                            $("#nothing").remove();
                            // 提交成功，创建节点
                            createRecordNode(res.data);
                            // 清空回复框
                            $("#content").val("");
                            $('#replyUser').addClass('hide').removeAttr('parent-id').children('span').text("");
                        } else {
                            // 提交失败
                            $.each(res.errors, function (k, v) {
                                $('#content').next('.error-msg').text(v[0]);
                            })
                        }
                    }
                })
            })
        }

        /* 绑定onchange事件 */
        function bindOnChange() {
            $('#addForm').find(".form-control").change(function () {
                var name = $(this).attr("name");
                if (name) {
                    var value = $(this).val();
                    var post_dict = {name: $(this).attr('name'), value: $(this).val()}
                    post_ajax(post_dict);
                }
            })
        }

        /* 问题描述保存按钮 */
        function saveDesc() {
            var post_dict = {name: 'desc', value: EDITOR.getValue()};
            post_ajax(post_dict);
        }

        /* 定义ajax提交方法 */
        function post_ajax(postdict) {
            //清空错误信息
            $("#id_" + postdict.name).parent().next(".error-msg").text("");
            $.ajax({
                url: IssuesChangeURL,
                type: "POST",
                data: JSON.stringify(postdict),
                dataType: "JSON",
                success: function (res) {
                    if (res.status) {
                        //
                        createRecordNode(res.data);
                    } else {
                        //显示错误信息
                        $("#id_" + postdict.name).parent().next(".error-msg").text(res.errors);
                    }
                }
            })
        }
    </script>
{% endblock %}